<template>
  <view class="popup-overlay" v-if="isVisible" @touchmove.stop.prevent>
    <view
        class="assistant-container"
        :class="{ 'slide-up': popupVisible, 'slide-down': !popupVisible }"
        :style="{ transform: `translateY(${translateY}px)` }"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
    >
      <!-- 顶部导航栏 -->
      <view class="header">
        <view class="header-left" @click="closePopup">
          <uni-icons type="closeempty" size="54rpx" color="#000" />
        </view>
        <image class="al-assistant-popup" src="/static/images/al-assistant.png"></image>
        <view class="header-info">
          <text class="title">XZHI助手</text>
          <text class="subtitle">知晓一切的XZHI助手~</text>
        </view>
        <view class="icons">
          <view class="icon" @click="toggleMute">
            <image
                class="icon-image"
                :src="isMuted ? '/static/images/shengyinguanbi.png' : '/static/images/shengyin.png'"
            ></image>
          </view>
          <view class="icon" @click="clearMessages">
            <image
                class="icon-image"
                src="/static/images/qingli.png"
            ></image>
          </view>
          <view class="icon more-options" @click="more">
            <image
                class="icon-image"
                src="/static/images/gengduo.png"
            ></image>
          </view>
        </view>
      </view>

      <!-- 聊天消息容器 -->
      <view class="chat-container-wrapper">
        <scroll-view
            class="chat-container"
            scroll-y="true"
            :scroll-top="scrollTop"
            @scroll="onScroll"
            ref="scrollView"
            id="scrollView"
        >
          <view class="message-wrapper" id="messageWrapper">
            <view class="welcome-message">
              <view class="welcome-content">
                <view class="welcome-text">
                  <text class="welcome-title">欢迎使用XZHI智能助手</text>
                  <text class="welcome-desc">我是您的专属AI助手，可以帮您解答实验室相关问题</text>
                </view>
              </view>
              <view class="quick-actions">
                <view class="action-item" @click="selectQuickAction('设备控制')">
                  <image class="icon-size" src="/static/images/shebeikongzhi.png"></image>
                  <text>设备控制</text>
                </view>
                <view class="action-item" @click="selectQuickAction('实验记录')">
                  <image class="icon-size" src="/static/images/shiyanjilu.png"></image>
                  <text>实验记录</text>
                </view>
                <view class="action-item" @click="selectQuickAction('常见问题')">
                  <image class="icon-size" src="/static/images/changjianwenti.png"></image>
                  <text>常见问题</text>
                </view>
              </view>
            </view>

            <view class="message-list">
              <!-- 欢迎消息 -->
              <view class="message-item assistant">
                <view class="message-content">
                  <view class="message-bubble">
                    <text class="message-text">您好！我是XZHI智能助手，您的专属实验助手。我可以帮您：
• 远程控制实验室设备
• 设置实验参数
• 解答实验问题
试试对我说：
• "将加热炉温度设为80℃"
• "查看搅拌机运行状态"
• "输出当前实验数据"
在下方输入指令开始实验吧！</text>
                  </view>
                  <view class="message-time">现在</view>
                </view>
              </view>

              <!-- 对话消息 -->
              <view
                  v-for="(message, index) in messages"
                  :key="index"
                  :class="['message-item', message.role === 'user' ? 'user' : 'assistant']"
              >
                <view class="message-content">
                  <view class="message-bubble">
                    <text v-if="!message.clickableLines" class="message-text">{{ message.content }}</text>
                    <view v-else class="clickable-lines-container">
                      <text 
                        v-for="(line, lineIndex) in message.clickableLines" 
                        :key="lineIndex"
                        :class="['message-text', 'clickable-line', line.type]"
                        @click="onLineClick(line)"
                      >{{ line.content }}</text>
                    </view>
                  </view>
                  <view class="message-time">{{ message.time }}</view>
                </view>
              </view>

              <!-- 加载状态 -->
              <view v-if="isLoading" class="message-item assistant">
                <view class="message-content">
                  <view class="message-bubble">
                    <view class="loading-dots">
                      <view class="dot"></view>
                      <view class="dot"></view>
                      <view class="dot"></view>
                    </view>
                  </view>
                </view>
              </view>
              <view class="scroll-bottom" id="scrollBottom"></view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 输入框区域 -->
      <view class="input-area">
        <view class="input-container">
          <input
              class="text-input"
              type="text"
              placeholder="有任何问题尽管问我"
              v-model="inputValue"
              @confirm="sendMessage"
              @focus="onInputFocus"
              @blur="onInputBlur"
          />
          <view class="action-buttons">
            <view
                v-if="showVoiceButton"
                class="voice-input"
                :class="{ recording: isRecording }"
                @touchstart="startRecording"
                @touchend="stopRecording"
                @touchcancel="cancelRecording"
            >
              <image class="icon-size-input" :src="isRecording ? '/static/images/voice-pulse.png' : '/static/images/yuyinshuru.png'"
              ></image>
            </view>
            <view
                v-else
                class="send-button"
                :class="{ active: inputValue.trim() }"
                @click="sendMessage"
            >
              <image class="icon-size-input" src="/static/images/fasong.png"></image>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {_assistant_help, _assistant_feature_intro} from '@/service/assistant.js';
export default {
  name: "AlAssistantPopup",
  data() {
    return {
      isVisible: false,
      popupVisible: false,
      inputValue: '',
      scrollTop: 0,
      scrollHeight: 0,
      isMuted: false,
      isDarkMode: false,
      isLoading: false,
      isScrollAtBottom: true,
      messages: [],
      messageListHeight: 0,
      showVoiceButton: true,
      isRecording: false,
      recordingTimer: null,
      recorderManager: null,
      serialnum: '', // 添加设备序列号
      currentUser: '',
      isKeyboardShown: false, // 键盘是否显示
      startY: 0,
      currentY: 0,
      translateY: 0,
      windowHeight: 0,
      isMoving: false,
      startTime: 0,
      storageKey: ''
    };
  },
  watch: {
    messages: {
      handler() {
        this.scrollToBottom();
        // 消息变化时保存
        if (this.isVisible) {
          this.saveMessages();
        }
      },
      deep: true
    },
    inputValue(newVal) {
      // 当输入框有内容时，显示发送按钮；否则显示语音按钮
      this.showVoiceButton = !newVal.trim();
    }
  },
  created() {
    // 获取当前用户信息
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.currentUser = userInfo.accountNum;
      console.log('当前用户：' + userInfo.accountNum);
    }

    // 获取窗口高度
    uni.getSystemInfo({
      success: (res) => {
        this.windowHeight = res.windowHeight;
      }
    });

    // 监听键盘高度变化
    // #ifdef H5
    // H5中监听窗口大小变化
    window.addEventListener('resize', this.handleWindowResize);
    // #endif
  },
  // #ifdef H5
  beforeDestroy() {
    window.removeEventListener('resize', this.handleWindowResize);
  },
  // #endif
  methods: {
    open(serialnum) {
      this.isVisible = true;
      this.serialnum = serialnum; // 获取设备序列号
      console.log('设备序列号：' + serialnum);

      // 每次打开时重新获取用户信息，确保信息是最新的
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo) {
        this.currentUser = userInfo.accountNum;
        console.log('当前用户：' + userInfo.accountNum);
      }

      // 设置存储键值
      this.storageKey = `assistant_messages_${this.currentUser}_${this.serialnum}`;
      
      // 加载保存的聊天记录
      this.loadMessages();

      // 延迟一小段时间再触发动画，确保DOM已经渲染
      this.$nextTick(() => {
        setTimeout(() => {
          this.popupVisible = true;
        }, 50);
      });
    },

    closePopup() {
      this.popupVisible = false;
      // 保存聊天记录
      this.saveMessages();
      // 等待动画结束后再隐藏整个弹窗
      setTimeout(() => {
        this.isVisible = false;
        // 重置位置
        this.translateY = 0;
      }, 300);
    },

    // 处理触摸开始事件
    handleTouchStart(e) {
      // 只在顶部区域滑动才触发关闭操作
      if (!e.touches || e.touches.length === 0) return;
      const touch = e.touches[0];
      const clientY = touch.clientY;

      // 如果触摸点在顶部100rpx范围内，则允许滑动关闭
      if (clientY < 200) {
        this.startY = touch.clientY;
        this.currentY = touch.clientY;
        this.startTime = new Date().getTime();
        this.isMoving = true;
      }
    },

    // 处理触摸移动事件
    handleTouchMove(e) {
      if (!this.isMoving) return;
      if (!e.touches || e.touches.length === 0) return;

      const touch = e.touches[0];
      this.currentY = touch.clientY;
      const moveY = this.currentY - this.startY;

      // 只允许向下拖拽
      if (moveY > 0) {
        this.translateY = moveY;
      }
    },

    // 处理触摸结束事件
    handleTouchEnd(e) {
      if (!this.isMoving) return;

      this.isMoving = false;
      const moveY = this.currentY - this.startY;
      const duration = new Date().getTime() - this.startTime;

      // 如果拖拽距离超过窗口高度的1/3或者快速滑动，则关闭弹窗
      if (moveY > this.windowHeight / 3 || (moveY > 50 && duration < 200)) {
        this.closePopup();
      } else {
        // 否则回到原位
        this.translateY = 0;
      }
    },

    // 输入框聚焦事件
    onInputFocus() {
      this.isKeyboardShown = true;
      // 延迟滚动到底部，确保键盘完全弹出
      setTimeout(() => {
        this.scrollToBottom();
      }, 300);
    },

    // 输入框失焦事件
    onInputBlur() {
      this.isKeyboardShown = false;
    },

    // #ifdef H5
    // 处理窗口大小变化（H5中用于检测键盘弹出/收起）
    handleWindowResize() {
      const currentHeight = window.innerHeight;
      const windowHeight = window.screen.height;

      // 如果当前高度小于屏幕高度的80%，认为键盘弹出
      if (currentHeight < windowHeight * 0.8) {
        this.isKeyboardShown = true;
      } else {
        this.isKeyboardShown = false;
      }

      // 滚动到底部
      setTimeout(() => {
        this.scrollToBottom();
      }, 100);
    },
    // #endif

    sendMessage() {
      if (!this.inputValue.trim()) return;

      // 添加用户消息
      const userMessage = {
        role: 'user',
        content: this.inputValue,
        time: this.getCurrentTime()
      };
      this.messages.push(userMessage);

      // 显示加载状态
      this.isLoading = true;
      this.scrollToBottom();

      // 调用AI接口获取回复
      this.getAIResponse(this.inputValue).then(response => {
        const assistantMessage = {
          role: 'assistant',
          content: response.content,
          time: this.getCurrentTime()
        };
        this.messages.push(assistantMessage);
        this.isLoading = false;
        this.scrollToBottom();

        // 如果有操作指令，则执行相应操作
        if (response.action) {
          this.$nextTick(() => {
            this.executeAction(response.action);
          });
        }
      }).catch(error => {
        console.error('AI助手请求失败:', error);
        const errorMessage = {
          role: 'assistant',
          content: '抱歉，我暂时无法回答您的问题，请稍后再试。',
          time: this.getCurrentTime()
        };
        this.messages.push(errorMessage);
        this.isLoading = false;
        this.scrollToBottom();
      });

      // 清空输入框
      this.inputValue = '';
    },

    clearMessages() {
      if (this.messages.length === 0) {
        uni.showToast({
          title: '暂无聊天记录',
          icon: 'none'
        });
        return;
      }
      
      uni.showModal({
        title: '确认清除',
        content: '确定要清除所有对话记录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清空消息列表，回到初始状态
            this.messages = [];
            // 同时清除保存的记录
            this.clearSavedMessages();
            uni.showToast({
              title: '对话记录已清除',
              icon: 'none'
            });
          }
        },
        // 设置z-index确保弹窗显示在最上层
        zIndex: 10005
      });
    },

    scrollToBottom() {
      // 始终尝试滚动到底部，不依赖 isScrollAtBottom 状态
      this.$nextTick(() => {
        // 使用 scroll-into-view 方式实现滚动到底部
        const query = uni.createSelectorQuery();
        query.select('#scrollBottom').boundingClientRect();
        query.select('#scrollView').boundingClientRect();
        query.exec((res) => {
          if (res[0] && res[1]) {
            // 增加一个小的延迟确保滚动操作在DOM更新后执行
            setTimeout(() => {
              this.scrollTop = res[0].top - res[1].top + this.scrollTop;
            }, 10);
          }
        });
      });
    },

    onScroll(e) {
      const { scrollTop, scrollHeight, offsetHeight } = e.detail;
      // 判断是否滚动到底部
      this.isScrollAtBottom = scrollTop + offsetHeight >= scrollHeight - 20;
    },

    toggleMute() {
      this.isMuted = !this.isMuted;
      uni.showToast({
        title: this.isMuted ? '已静音' : '已开启声音',
        icon: 'none'
      });
      // 图标会根据 isMuted 的值自动切换
      // isMuted 为 true 时显示 icon-mute（静音图标）
      // isMuted 为 false 时显示 icon-volume（音量图标）
    },

    startVoiceInput() {
      uni.showToast({
        title: '语音输入功能开发中',
        icon: 'none'
      });
    },

    getCurrentTime() {
      const now = new Date();
      return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    },

    // 调用AI接口获取回复
    async getAIResponse(userInput) {
      try {
        const response = await _assistant_help({
          message: userInput,
          serialnum: this.serialnum+ ":" + this.currentUser
        });
        console.log('AI助手请求参数:', {
          message: userInput,
          serialnum: this.serialnum+ ":" + this.currentUser
        });
        console.log('AI助手返回数据:', response);
        if (response && response.data) {
          return {
            content: response.data.content || response.data || '抱歉，我没有理解您的意思。',
            action: response.data.action || null
          };
        } else {
          return {
            content: '抱歉，我没有理解您的意思。',
            action: null
          };
        }
      } catch (error) {
        console.error('AI助手请求失败:', error);
        throw error;
      }
    },

    // 执行操作指令
    executeAction(action) {
      switch (action.type) {
        case 'NAVIGATE':
          // 页面跳转操作
          if (action.url) {
            uni.navigateTo({
              url: action.url
            });
          }
          break;

        case 'TOAST':
          // 显示提示信息
          uni.showToast({
            title: action.message || '操作完成',
            icon: 'none'
          });
          break;

        case 'MODAL':
          // 显示模态框
          uni.showModal({
            title: action.title || '提示',
            content: action.content || '',
            showCancel: action.showCancel || false,
            confirmText: action.confirmText || '确定',
            cancelText: action.cancelText || '取消'
          });
          break;

        default:
          console.log('未知操作类型:', action.type);
      }
    },

    selectQuickAction(action) {
      // 根据不同的action构造用户提问
      const userMessage = {
        role: 'user',
        content: `请介绍一下${action}功能`,
        time: this.getCurrentTime()
      };
      this.messages.push(userMessage);
      
      // 显示加载状态
      this.isLoading = true;
      this.scrollToBottom();
      
      // 调用接口获取功能介绍
      _assistant_feature_intro(action).then(response => {
        let content = '';
        let clickableLines = null;
        
        if (response && response.length > 0) {
          // 将所有介绍项合并成一个消息
          content = response.join('\n');
          // 创建可点击行
          clickableLines = response.map(item => ({
            content: item,
            type: 'question',
            action: 'question'
          }));
        } else {
          content = `暂无${action}的相关介绍内容。`;
        }
        
        const assistantMessage = {
          role: 'assistant',
          content: content,
          clickableLines: clickableLines,
          time: this.getCurrentTime()
        };
        this.isLoading = false;
        this.messages.push(assistantMessage);
        this.scrollToBottom();
      }).catch(error => {
        console.error('获取功能介绍失败:', error);
        const errorMessage = {
          role: 'assistant',
          content: `获取${action}介绍时发生错误，请稍后重试。`,
          time: this.getCurrentTime()
        };
        this.isLoading = false;
        this.messages.push(errorMessage);
        this.scrollToBottom();
      });
    },
    
    // 处理行点击事件
    onLineClick(line) {
      if (line.action === 'question') {
        // 将点击的内容作为用户问题发送
        const userMessage = {
          role: 'user',
          content: line.content,
          time: this.getCurrentTime()
        };
        this.messages.push(userMessage);
        
        // 显示加载状态
        this.isLoading = true;
        this.scrollToBottom();
        
        // 调用AI接口获取回复
        this.getAIResponse(line.content).then(response => {
          const assistantMessage = {
            role: 'assistant',
            content: response.content,
            time: this.getCurrentTime()
          };
          this.messages.push(assistantMessage);
          this.isLoading = false;
          this.scrollToBottom();
          
          // 如果有操作指令，则执行相应操作
          if (response.action) {
            this.$nextTick(() => {
              this.executeAction(response.action);
            });
          }
        }).catch(error => {
          console.error('AI助手请求失败:', error);
          const errorMessage = {
            role: 'assistant',
            content: '抱歉，我暂时无法回答您的问题，请稍后再试。',
            time: this.getCurrentTime()
          };
          this.messages.push(errorMessage);
          this.isLoading = false;
          this.scrollToBottom();
        });
      }
    },

    // 开始录音
    startRecording() {
      // 检查平台是否支持录音功能
      // #ifdef H5
      uni.showToast({
        title: '当前平台不支持语音输入',
        icon: 'none'
      });
      return;
      // #endif

      // 显示操作提示
      uni.showToast({
        title: '按住说话',
        icon: 'none',
        duration: 1000
      });

      // 请求麦克风权限后开始录音
      this.requestMicrophonePermission(() => {
        // 初始化录音管理器
        this.initRecorderManager();

        // 开始录音
        this.recorderManager.start({
          format: 'mp3'
        });

        this.isRecording = true;

        // 设置最长录音时间（10秒）
        this.recordingTimer = setTimeout(() => {
          this.stopRecording();
        }, 10000);
      });
    },

    // 停止录音
    stopRecording() {
      if (this.isRecording) {
        this.isRecording = false;
        clearTimeout(this.recordingTimer);
        this.recorderManager.stop();

        // 显示录音结束提示
        uni.showToast({
          title: '正在识别语音...',
          icon: 'none',
          duration: 1000
        });
      }
    },

    // 取消录音
    cancelRecording() {
      if (this.isRecording) {
        this.isRecording = false;
        clearTimeout(this.recordingTimer);
        this.recorderManager.stop();
        uni.showToast({
          title: '已取消录音',
          icon: 'none'
        });
      }
    },

    // 请求麦克风权限
    requestMicrophonePermission(callback) {
      const platform = uni.getSystemInfoSync().platform;

      // 在App端请求麦克风权限
      if (platform === 'android' || platform === 'ios') {
        // #ifdef APP-PLUS
        // 先显示权限说明
        uni.showModal({
          title: '权限说明',
          content: '语音输入功能需要访问您的麦克风，用于录制语音并转换为文字。我们不会收集或存储您的语音信息。',
          showCancel: true,
          confirmText: '同意',
          cancelText: '拒绝',
          success: (res) => {
            if (res.confirm) {
              // 用户同意后请求权限
              const permissions = ['android.permission.RECORD_AUDIO'];
              plus.android.requestPermissions(permissions, (resultObj) => {
                let result = 0;
                for (let i = 0; i < resultObj.granted.length; i++) {
                  result = 1;
                }
                for (let i = 0; i < resultObj.deniedPresent.length; i++) {
                  result = 0;
                }
                for (let i = 0; i < resultObj.deniedAlways.length; i++) {
                  result = -1;
                }

                if (result <= 0) {
                  // 显示更友好的权限引导对话框
                  uni.showModal({
                    title: '需要麦克风权限',
                    content: '语音输入功能需要访问您的麦克风，请在设置中开启麦克风权限',
                    showCancel: true,
                    confirmText: '去设置',
                    cancelText: '取消',
                    success: (res) => {
                      if (res.confirm) {
                        // 引导用户去设置页面开启权限
                        if (plus.os.name === 'Android') {
                          const Intent = plus.android.importClass('android.content.Intent');
                          const Settings = plus.android.importClass('android.provider.Settings');
                          const main = plus.android.runtimeMainActivity();
                          const intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                          const uri = plus.android.invoke('android.net.Uri', 'fromParts', 'package', main.getPackageName(), null);
                          plus.android.invoke(intent, 'setData', uri);
                          main.startActivity(intent);
                        } else if (plus.os.name === 'iOS') {
                          // iOS跳转到设置页面
                          const UIApplication = plus.ios.importClass("UIApplication");
                          const application2 = UIApplication.sharedApplication();
                          const NSURL2 = plus.ios.importClass("NSURL");
                          const setting2 = NSURL2.URLWithString("app-settings:");
                          application2.openURL(setting2);
                          plus.ios.deleteObject(setting2);
                          plus.ios.deleteObject(NSURL2);
                          plus.ios.deleteObject(application2);
                          plus.ios.deleteObject(UIApplication);
                        }
                      } else if (res.cancel) {
                        // 用户取消授权，显示提示信息
                        uni.showToast({
                          title: '未获得麦克风权限，无法使用语音输入',
                          icon: 'none',
                          duration: 2000
                        });
                      }
                    }
                  });
                } else {
                  callback && callback();
                }
              }, (error) => {
                console.error('权限请求失败：' + error.message);
                uni.showToast({
                  title: '权限请求失败',
                  icon: 'none'
                });
              });
            } else if (res.cancel) {
              // 用户拒绝授权
              uni.showToast({
                title: '未获得麦克风权限，无法使用语音输入',
                icon: 'none',
                duration: 2000
              });
            }
          }
        });
        // #endif

        // #ifndef APP-PLUS
        // 在H5或小程序中，录音权限会在需要时自动请求
        callback && callback();
        // #endif
      } else {
        callback && callback();
      }
    },

    // 初始化录音管理器
    initRecorderManager() {
      if (!this.recorderManager) {
        // #ifdef H5
        // H5不支持录音功能
        uni.showToast({
          title: '当前平台不支持语音输入',
          icon: 'none'
        });
        return;
        // #endif

        // #ifndef H5
        this.recorderManager = uni.getRecorderManager();

        // 监听录音开始事件
        this.recorderManager.onStart(() => {
          console.log('开始录音');
        });

        // 监听录音结束事件
        this.recorderManager.onStop((res) => {
          console.log('录音结束，文件路径：' + res.tempFilePath);
          // 模拟语音识别结果
          this.handleVoiceResult();
        });

        // 监听录音错误事件
        this.recorderManager.onError((res) => {
          console.error('录音失败：' + JSON.stringify(res));
          uni.showToast({
            title: '录音失败',
            icon: 'none'
          });
          this.isRecording = false;
        });
        // #endif
      }
    },

    // 处理语音识别结果（模拟）
    handleVoiceResult() {
      // 模拟语音识别结果
      const voiceTexts = [
        '你好，我想了解一下设备管理功能',
        '请问如何添加新的实验记录？',
        '请介绍一下常见问题有哪些？',
        '我想了解一下设备控制相关的内容',
        '如何查看我的实验历史记录？'
      ];

      const randomText = voiceTexts[Math.floor(Math.random() * voiceTexts.length)];
      this.inputValue = randomText;
      this.sendMessage();
    },

    more() {
      // 更多操作功能
      uni.showToast({
        title: '更多功能开发中',
        icon: 'none'
      });
    },

    // 保存聊天记录
    saveMessages() {
      if (this.storageKey) {
        try {
          uni.setStorageSync(this.storageKey, this.messages);
        } catch (e) {
          console.error('保存聊天记录失败:', e);
        }
      }
    },

    // 加载聊天记录
    loadMessages() {
      if (this.storageKey) {
        try {
          const savedMessages = uni.getStorageSync(this.storageKey);
          if (savedMessages && Array.isArray(savedMessages)) {
            this.messages = savedMessages;
          } else {
            // 如果没有保存的记录，则初始化为空数组
            this.messages = [];
          }
        } catch (e) {
          console.error('加载聊天记录失败:', e);
          this.messages = [];
        }
      } else {
        this.messages = [];
      }
    },

    // 清除保存的聊天记录
    clearSavedMessages() {
      if (this.storageKey) {
        try {
          uni.removeStorageSync(this.storageKey);
        } catch (e) {
          console.error('清除聊天记录失败:', e);
        }
      }
    }
  }
};
</script>

<style scoped>
.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 9999;
}

.assistant-container {
  position: absolute;
  top: 8%;
  left: 0;
  width: 100%;
  height: 92vh;
  border-radius: 30rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  overflow: hidden;
  z-index: 10000;
  transition: transform 0.3s ease-out;
}

.assistant-container.slide-up {
  transform: translateY(0);
}

.assistant-container.slide-down {
  transform: translateY(100%);
}

.header {
  position: absolute;
  //bottom: 90%;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 40rpx 30rpx 20rpx 30rpx;
  background: linear-gradient(180deg, #f0fbff 0%, #f1f5fa 100%);
  color: black;
  z-index: 100;
}

.header-left {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.header .al-assistant-popup {
  width: 70rpx;
  height: 70rpx;
  margin-right: 20rpx;
  z-index: 999;
  border-radius: 50%;
  box-shadow: 0 2rpx 30rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.header .header-info {
  flex: 1;
}

.header .header-info .title {
  font-size: 30rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 6rpx;
}

.header .header-info .subtitle {
  font-size: 20rpx;
  opacity: 0.9;
}

.header .icons {
  display: flex;
  align-items: center;
}

.header .icons .icon {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
  font-size: 36rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  transition: background 0.3s;
}

.icon-image {
  width: 100%;
  height: 100%;
}

.header .icons .icon:active {
  background: rgba(255, 255, 255, 0.3);
}

.chat-container-wrapper {
  position: fixed;
  top: 180rpx; /* header高度 */
  left: 0;
  right: 0;
  bottom: 120rpx; /* input-area高度 */
  z-index: 10;
}

.chat-container {
  height: 100%;
}

.message-wrapper {
  padding: 0 30rpx;
  padding-bottom: 20rpx;
}

.welcome-message {
  background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(100, 149, 237, 0.15);
  position: relative;
  overflow: hidden;
}

.welcome-message::before {
  content: "";
  position: absolute;
  top: -50rpx;
  right: -50rpx;
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(74, 144, 226, 0.1) 0%, rgba(99, 179, 237, 0.05) 100%);
}

.welcome-message::after {
  content: "";
  position: absolute;
  bottom: -80rpx;
  right: -20rpx;
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(74, 144, 226, 0.05) 0%, rgba(99, 179, 237, 0.02) 100%);
}

.welcome-message .welcome-content {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  position: relative;
  z-index: 2;
}

.welcome-message .welcome-text {
  flex: 1;
}

.welcome-message .welcome-text .welcome-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.welcome-message .welcome-text .welcome-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 40rpx;
}

.welcome-message .quick-actions {
  display: flex;
  justify-content: space-between;
  position: relative;
  z-index: 2;
}

.welcome-message .quick-actions .action-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 25rpx 10rpx;
  background: white;
  border-radius: 16rpx;
  margin: 0 10rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
}

.welcome-message .quick-actions .action-item:first-child {
  margin-left: 0;
}

.welcome-message .quick-actions .action-item:last-child {
  margin-right: 0;
}

.welcome-message .quick-actions .action-item:active {
  transform: scale(0.95);
}

.welcome-message .quick-actions .action-item .iconfont {
  font-size: 48rpx;
  margin-bottom: 15rpx;
  color: #4A90E2;
}

.welcome-message .quick-actions .action-item text {
  font-size: 24rpx;
  color: #555;
}

.icon-size {
  width: 70rpx;
  height: 70rpx;
  margin-bottom: 15rpx;
}

.icon-size-input {
  width: 50rpx;
  height: 50rpx;
}

.message-list {
  padding-bottom: 20rpx;
}

.message-item {
  display: flex;
  margin-bottom: 30rpx;
  max-width: 100%;
}

.message-item.assistant {
  align-items: flex-start;
  margin-right: auto;
}

.message-item.user {
  align-items: flex-end;
  margin-left: auto;
  justify-content: flex-end;
}

.message-item .message-content {
  display: flex;
  flex-direction: column;
  max-width: 80%;
}

.message-item.user .message-content {
  flex-direction: column-reverse;
}

.message-item .message-content .message-bubble {
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  max-width: 100%;
  word-wrap: break-word;
}

.message-item .message-content .message-text {
  font-size: 28rpx;
  line-height: 42rpx;
  white-space: pre-wrap;
  word-break: break-word;
}

.clickable-line {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8rpx;
  padding: 4rpx 8rpx;
  margin: 4rpx 0;
  display: block;
  text-decoration: underline;
}

.clickable-line.question:hover {
  background-color: #f0f8ff;
  box-shadow: 0 2rpx 8rpx rgba(74, 144, 226, 0.2);
}

.clickable-line.question:active {
  transform: translateY(2rpx);
  box-shadow: 0 0rpx 4rpx rgba(74, 144, 226, 0.3);
}

.message-item.assistant .message-content .message-bubble {
  background-color: white;
  border-top-left-radius: 0;
}

.message-item.assistant .message-content .message-text {
  color: #333;
  text-align: left;
}

.message-item.user .message-content .message-bubble {
  background: linear-gradient(90deg, #4A90E2 0%, #63B3ED 100%);
  border-top-right-radius: 0;
}

.message-item.user .message-content .message-text {
  color: white;
  text-align: right;
}

.message-item .message-content .message-time {
  font-size: 20rpx;
  color: #999;
  margin-top: 10rpx;
}

.message-item.assistant .message-content .message-time {
  align-self: flex-start;
}

.message-item.user .message-content .message-time {
  align-self: flex-end;
}

.loading-dots {
  display: flex;
  align-items: center;
}

.loading-dots .dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #4A90E2;
  margin: 0 8rpx;
  animation: loading 1.5s infinite ease-in-out;
}

.loading-dots .dot:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots .dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1.0);
  }
}

.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: white;
  border-top: 1rpx solid #e5e5e5;
  z-index: 100;
}

.input-area .input-container {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 50rpx;
  padding: 10rpx 20rpx;
}

.input-area .input-container .text-input {
  flex: 1;
  padding: 15rpx 20rpx;
  font-size: 28rpx;
  background: transparent;
}

.input-area .input-container .action-buttons {
  display: flex;
  align-items: center;
}

.input-area .input-container .action-buttons .voice-input,
.input-area .input-container .action-buttons .send-button {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 15rpx;
  font-size: 36rpx;
  transition: all 0.3s;
  cursor: pointer;
}

.input-area .input-container .action-buttons .voice-input {
  background-color: #e3f2fd;
  color: #4A90E2;
  position: relative;
}

.input-area .input-container .action-buttons .voice-input::after {
  content: "按住说话";
  position: absolute;
  top: -50rpx;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.3s;
  pointer-events: none;
}

.input-area .input-container .action-buttons .voice-input:hover::after,
.input-area .input-container .action-buttons .voice-input:active::after {
  opacity: 1;
}

.input-area .input-container .action-buttons .voice-input.recording {
  background-color: #ff4d4f;
  color: white;
  animation: pulse 1.5s infinite;
}

.input-area .input-container .action-buttons .voice-input.recording::after {
  content: "松开结束";
  opacity: 1;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.input-area .input-container .action-buttons .send-button {
  background-color: #e3f2fd;
  color: #4A90E2;
}

/*.input-area .input-container .action-buttons .send-button.active {*/
/*  background: linear-gradient(90deg, #4A90E2 0%, #63B3ED 100%);*/
/*  color: white;*/
//  transform: scale(1.05);
//}
</style>